package pipeline

import "github.com/gin-gonic/gin"

type (
	Middleware[Payload any] func(*gin.Context, Payload) error
	Pipeline[Payload any]   struct {
		payload Payload
		pipes   []Middleware[Payload]
		ctx     *gin.Context
	}
)

func New[Input any]() *Pipeline[Input] {
	return &Pipeline[Input]{}
}

// Send 发送业务载体
func (p *Pipeline[Payload]) Send(ctx *gin.Context, input Payload) *Pipeline[Payload] {
	p.ctx = ctx
	p.payload = input
	return p
}

// Through 通过许多中间件
func (p *Pipeline[Payload]) Through(pipes ...Middleware[Payload]) *Pipeline[Payload] {
	p.pipes = pipes
	return p
}

// Then 然后执行一个方法并返回错误
func (p *Pipeline[Payload]) Then(f func(ctx *gin.Context, payload Payload) error) error {
	//逐个穿过中间件
	for _, o := range p.pipes {
		if err := o(p.ctx, p.payload); err != nil {
			return err
		}
	}
	return f(p.ctx, p.payload)
}
